import store from '../../store'
import { MessageBox, Message } from 'element-ui'

const HandleMeasure = {
  stickMeasureId: 1, // 贴地测量 id
  endPoint: [], // 鼠标移动位置
  positions: [], // 点击记录点位信息
  DynamicLine: null, // 动态线实体
  ispickUpCoordinate: false, // 是否选取坐标
  handleStickMeasure() {
    // 取消双击事件-追踪该位置
    // viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
    var positions = []
    var poly = null
    // var tooltip = document.getElementById("toolTip");
    var distance = 0
    var cartesian = null
    var floatingPoint = null
    var stickMeasureID = 1
    // tooltip.style.display = "block";

    handler.setInputAction(function (movement) {
      // tooltip.style.left = movement.endPosition.x + 3 + "px";
      // tooltip.style.top = movement.endPosition.y - 25 + "px";
      // tooltip.innerHTML = '<p>单击开始，右击结束</p>';
      // cartesian = viewer.scene.pickPosition(movement.endPosition);
      const ray = viewer.camera.getPickRay(movement.endPosition)
      cartesian = viewer.scene.globe.pick(ray, viewer.scene)
      // cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
      if (positions.length >= 2) {
        if (!Cesium.defined(poly)) {
          poly = new PolyLinePrimitive(positions)
        } else {
          positions.pop()
          // cartesian.y += (1 + Math.random());
          positions.push(cartesian)
        }
        distance = getSpaceDistance(positions)
        // tooltip.innerHTML='<p>'+distance+'米</p>';
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    handler.setInputAction(function (movement) {
      // tooltip.style.display = "none";
      // cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
      // cartesian = viewer.scene.pickPosition(movement.position);
      const ray = viewer.camera.getPickRay(movement.position)
      cartesian = viewer.scene.globe.pick(ray, viewer.scene)
      if (positions.length === 0) {
        positions.push(cartesian.clone())
      }
      positions.push(cartesian)
      // 在三维场景中添加Label
      //   var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      var textDisance = distance + '米'
      floatingPoint = viewer.entities.add({
        id: 'distanceId' + stickMeasureID++,
        name: '空间直线距离',
        // position: Cesium.Cartesian3.fromDegrees(cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180,cartographic.height),
        position: positions[positions.length - 1],
        point: {
          pixelSize: 8,
          color: Cesium.Color.DEEPSKYBLUE,
          outlineColor: Cesium.Color.GOLD,
          outlineWidth: 2,
          depthFailMaterial: Cesium.Color.BLUE, // 位于地下的材质,不给地下的材质，位于地下的线就不可见
          clampToGround: true // 折线固定在地面
        },
        label: {
          text: textDisance,
          font: '12pt Source Han Sans CN', // 字体样式
          fillColor: Cesium.Color.WHITE, // 字体颜色
          backgroundColor: Cesium.Color.BLACK, // 背景颜色
          showBackground: true, // 是否显示背景颜色
          style: Cesium.LabelStyle.FILL, // label样式
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.CENTER, // 垂直位置
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT, // 水平位置
          pixelOffset: new Cesium.Cartesian2(0.0, 20),
          depthFailMaterial: Cesium.Color.BLUE, // 位于地下的材质,不给地下的材质，位于地下的线就不可见
          clampToGround: true // 折线固定在地面
        }
      })
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    handler.setInputAction(function (movement) {
      handler.destroy() // 关闭事件句柄
      positions.pop() // 最后一个点无效
      // HandleMeasure.ispickUpCoordinate = false
      // this.handlePickCoordinate()
      // viewer.cesiumWidget.screenSpaceEventHandler.setInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    var doubleHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
    doubleHandler.setInputAction(function (movement) {
      var pick = viewer.scene.pick(movement.position)
      if (Cesium.defined(pick) && pick.id._id) {
        var box = viewer.entities.getById(pick.id._id)
        viewer.entities.remove(box)
        for (let i = stickMeasureID - 1; i >= 0; i--) {
          const box1 = viewer.entities.getById('distanceId' + i)
          viewer.entities.remove(box1)
        }
        // if (positions.length.length === 2) {
        //     var box2 = viewer.entities.getById('distanceId' + (stickMeasureID - 2))
        //     viewer.entities.remove(box2)
        // }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)

    var PolyLinePrimitive = (function () {
      function _(positions) {
        this.options = {
          name: '直线',
          polyline: {
            show: true,
            positions: [],
            // material: Cesium.Color.CHARTREUSE,
            // width: 10,
            // clampToGround: true
            width: 6,
            // material: Cesium.Color.RED,
            material: new Cesium.PolylineGlowMaterialProperty({
              color: Cesium.Color.GOLD,
              glowPower: 0.25
            }),
            // depthFailMaterial: Cesium.Color.BLUE,//位于地下的材质,不给地下的材质，位于地下的线就不可见
            clampToGround: true // 折线固定在地面
          }
        }
        this.positions = positions
        this._init()
      }

      _.prototype._init = function () {
        var _self = this
        var _update = function () {
          return _self.positions
        }
        // 实时更新polyline.positions
        this.options.polyline.positions = new Cesium.CallbackProperty(_update, false)
        viewer.entities.add(this.options)
      }

      return _
    })()

    // 空间两点距离计算函数
    function getSpaceDistance(positions) {
      var distance = 0
      for (var i = 0; i < positions.length - 1; i++) {
        var point1cartographic = Cesium.Cartographic.fromCartesian(positions[i])
        var point2cartographic = Cesium.Cartographic.fromCartesian(positions[i + 1])
        /** 根据经纬度计算出距离**/
        var geodesic = new Cesium.EllipsoidGeodesic()
        geodesic.setEndPoints(point1cartographic, point2cartographic)
        var s = geodesic.surfaceDistance
        // 返回两点之间的距离
        s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2))
        distance = distance + s
      }
      return distance.toFixed(2)
    }
  },

  handleAreaSpace() {
    // 取消双击事件-追踪该位置
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
    // 鼠标事件
    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene._imageryLayerCollection)
    var positions = []
    var tempPoints = []
    var polygon = null
    // var tooltip = document.getElementById("toolTip");
    var cartesian = null
    var floatingPoint// 浮动点
    // tooltip.style.display = "block";

    handler.setInputAction(function (movement) {
      // tooltip.style.left = movement.endPosition.x + 3 + "px";
      // tooltip.style.top = movement.endPosition.y - 25 + "px";
      // tooltip.innerHTML ='<p>单击开始，右击结束</p>';
      // cartesian = viewer.scene.pickPosition(movement.endPosition);
      const ray = viewer.camera.getPickRay(movement.endPosition)
      cartesian = viewer.scene.globe.pick(ray, viewer.scene)
      // cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
      if (positions.length >= 2) {
        if (!Cesium.defined(polygon)) {
          polygon = new PolygonPrimitive(positions)
        } else {
          positions.pop()
          // cartesian.y += (1 + Math.random());
          positions.push(cartesian)
        }
        // tooltip.innerHTML='<p>'+distance+'米</p>';
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    handler.setInputAction(function (movement) {
      // tooltip.style.display = "none";
      // cartesian = viewer.scene.pickPosition(movement.position);
      const ray = viewer.camera.getPickRay(movement.position)
      cartesian = viewer.scene.globe.pick(ray, viewer.scene)
      // cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
      if (positions.length == 0) {
        positions.push(cartesian.clone())
      }
      // positions.pop();
      positions.push(cartesian)
      // 在三维场景中添加点
      var cartographic = Cesium.Cartographic.fromCartesian(positions[positions.length - 1])
      var longitudeString = Cesium.Math.toDegrees(cartographic.longitude)
      var latitudeString = Cesium.Math.toDegrees(cartographic.latitude)
      var heightString = cartographic.height
      tempPoints.push({ lon: longitudeString, lat: latitudeString, hei: heightString })
      floatingPoint = viewer.entities.add({
        name: '多边形面积',
        position: positions[positions.length - 1],
        point: {
          pixelSize: 5,
          color: Cesium.Color.RED,
          outlineColor: Cesium.Color.WHITE,
          outlineWidth: 2,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          depthFailMaterial: Cesium.Color.BLUE, // 位于地下的材质,不给地下的材质，位于地下的线就不可见
          clampToGround: true // 折线固定在地面
        }
      })
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    handler.setInputAction(function (movement) {
      handler.destroy()
      positions.pop()
      // tempPoints.pop();
      // viewer.entities.remove(floatingPoint);
      // tooltip.style.display = "none";
      // 在三维场景中添加点
      // var cartographic = Cesium.Cartographic.fromCartesian(positions[positions.length - 1]);
      // var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
      // var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
      // var heightString = cartographic.height;
      // tempPoints.push({ lon: longitudeString, lat: latitudeString ,hei:heightString});

      var textArea = getArea(tempPoints) + '平方公里'
      viewer.entities.add({
        name: '多边形面积',
        position: positions[positions.length - 1],
        clampToGround: true, // 折线固定在地面
        // point : {
        //  pixelSize : 5,
        //  color : Cesium.Color.RED,
        //  outlineColor : Cesium.Color.WHITE,
        //  outlineWidth : 2,
        //  heightReference:Cesium.HeightReference.CLAMP_TO_GROUND
        // },
        label: {
          text: textArea,
          font: '18px sans-serif',
          fillColor: Cesium.Color.GOLD,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(20, -40),
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          clampToGround: true // 折线固定在地面
        }
      })
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)

    var radiansPerDegree = Math.PI / 180.0// 角度转化为弧度(rad)
    var degreesPerRadian = 180.0 / Math.PI// 弧度转化为角度

    // 计算多边形面积
    function getArea(points) {
      var res = 0
      // 拆分三角曲面

      for (var i = 0; i < points.length - 2; i++) {
        var j = (i + 1) % points.length
        var k = (i + 2) % points.length
        var totalAngle = Angle(points[i], points[j], points[k])

        var dis_temp1 = distance(positions[i], positions[j])
        var dis_temp2 = distance(positions[j], positions[k])
        res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle))
      }

      return (res / 1000000.0).toFixed(4)
    }

    /* 角度*/
    function Angle(p1, p2, p3) {
      var bearing21 = Bearing(p2, p1)
      var bearing23 = Bearing(p2, p3)
      var angle = bearing21 - bearing23
      if (angle < 0) {
        angle += 360
      }
      return angle
    }
    /* 方向*/
    function Bearing(from, to) {
      var lat1 = from.lat * radiansPerDegree
      var lon1 = from.lon * radiansPerDegree
      var lat2 = to.lat * radiansPerDegree
      var lon2 = to.lon * radiansPerDegree
      var angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2))
      if (angle < 0) {
        angle += Math.PI * 2.0
      }
      angle = angle * degreesPerRadian// 角度
      return angle
    }

    var PolygonPrimitive = (function () {
      function _(positions) {
        this.options = {
          name: '多边形',
          polygon: {
            hierarchy: [],
            // perPositionHeight : true,
            material: Cesium.Color.GREEN.withAlpha(0.5),
            // depthFailMaterial:Cesium.Color.BLUE,//位于地下的材质,不给地下的材质，位于地下的线就不可见
            clampToGround: true // 折线固定在地面
            // heightReference:20000
          }
        }

        this.hierarchy = { positions }
        this._init()
      }

      _.prototype._init = function () {
        var _self = this
        var _update = function () {
          return _self.hierarchy
        }
        // 实时更新polygon.hierarchy
        this.options.polygon.hierarchy = new Cesium.CallbackProperty(_update, false)
        viewer.entities.add(this.options)
      }

      return _
    })()

    function distance(point1, point2) {
      var point1cartographic = Cesium.Cartographic.fromCartesian(point1)
      var point2cartographic = Cesium.Cartographic.fromCartesian(point2)
      /** 根据经纬度计算出距离**/
      var geodesic = new Cesium.EllipsoidGeodesic()
      geodesic.setEndPoints(point1cartographic, point2cartographic)
      var s = geodesic.surfaceDistance
      // 返回两点之间的距离
      s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2))
      return s
    }
  },

  // 贴地测量
  handleStickMeasure1() {
    HandleMeasure.positions = []
    HandleMeasure.DynamicLine = null
    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
    viewer.clock.shouldAnimate = true
    HandleMeasure.drawDynamicLine()
    //
    // 鼠标左键单击事件
    handler.setInputAction((movement) => {
      // 取消双击事件-追踪该位置
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
      // movement.position  屏幕坐标
      // viewer.scene.globe.ellipsoid 笛卡尔坐标
      var cartesian2 = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid)
      // cartesian2  射线到球体的交点的 笛卡尔坐标点
      // cartographic  根据笛卡尔坐标点，获取经纬度的弧度值
      var cartographic = Cesium.Cartographic.fromCartesian(cartesian2)
      // 将弧度值转为经纬度
      var lng = Cesium.Math.toDegrees(cartographic.longitude)// 经度值
      var lat = Cesium.Math.toDegrees(cartographic.latitude)// 纬度值
      HandleMeasure.positions.push([lng, lat])

      viewer.entities.add({
        position: cartesian2,
        point: {
          pixelSize: 8,
          color: Cesium.Color.DEEPSKYBLUE,
          outlineColor: Cesium.Color.GOLD,
          outlineWidth: 2
        }
      })
      // 创建动态线
      if (HandleMeasure.positions.length >= 2) {
        const n = HandleMeasure.positions.length
        var pos = [HandleMeasure.positions[n - 2][0], HandleMeasure.positions[n - 2][1], HandleMeasure.positions[n - 1][0], HandleMeasure.positions[n - 1][1]]
        HandleMeasure.drawTheLine(pos)
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    // 鼠标移动事件
    handler.setInputAction((movement) => {
      if (!HandleMeasure.positions.length) return
      // viewer.scene.globe.ellipsoid 笛卡尔坐标
      var cartesian2 = viewer.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid)
      // cartesian2  射线到球体的交点的 笛卡尔坐标点
      // cartographic  根据笛卡尔坐标点，获取经纬度的弧度值
      var cartographic = Cesium.Cartographic.fromCartesian(cartesian2)
      // 将弧度值转为经纬度
      var lng = Cesium.Math.toDegrees(cartographic.longitude)// 经度值
      var lat = Cesium.Math.toDegrees(cartographic.latitude)// 纬度值
      HandleMeasure.endPoint[0] = lng
      HandleMeasure.endPoint[1] = lat
      viewer.scene.postProcessStages.fxaa.enabled = false // 去锯齿
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    // 右键取消测量
    handler.setInputAction((movement) => {
      viewer.entities.remove(HandleMeasure.DynamicLine)
      HandleMeasure.DynamicLine = null
      handler.destroy()
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    var doubleHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
    doubleHandler.setInputAction(function (movement) {
      var pick = viewer.scene.pick(movement.position)
      if (Cesium.defined(pick) && pick.id._id) {
        var box = viewer.entities.getById(pick.id._id)
        viewer.entities.remove(box)
      }
    }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
  },
  // 将点连城线
  drawTheLine(positions) {
    // const d = HandleMeasure.surfaceDistance(positions)
    viewer.entities.add({
      id: 'measureLine' + HandleMeasure.stickMeasureId++,
      name: 'measureLine',
      polyline: {
        show: true,
        positions: Cesium.Cartesian3.fromDegreesArray(positions),
        width: 6,
        // material: Cesium.Color.RED,
        material: new Cesium.PolylineGlowMaterialProperty({
          color: Cesium.Color.GOLD,
          glowPower: 0.25
        })
      }
    })
    viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(positions[2], positions[3]),
      label: {
        text: HandleMeasure.setDistance(HandleMeasure.surfaceDistance(positions)),
        font: '12pt Source Han Sans CN', // 字体样式
        fillColor: Cesium.Color.WHITE, // 字体颜色
        backgroundColor: Cesium.Color.BLACK, // 背景颜色
        showBackground: true, // 是否显示背景颜色
        style: Cesium.LabelStyle.FILL, // label样式
        outlineWidth: 2,
        verticalOrigin: Cesium.VerticalOrigin.CENTER, // 垂直位置
        horizontalOrigin: Cesium.HorizontalOrigin.LEFT, // 水平位置
        pixelOffset: new Cesium.Cartesian2(0.0, 20)
      }
    })
  },
  updateEndPoint(time, result) {
    if (!HandleMeasure.endPoint[0] || !HandleMeasure.endPoint[1] || HandleMeasure.positions.length === 0) {
      return []
    } else {
      const n = HandleMeasure.positions.length - 1
      return Cesium.Cartesian3.fromDegreesArray([HandleMeasure.positions[n][0], HandleMeasure.positions[n][1], HandleMeasure.endPoint[0], HandleMeasure.endPoint[1]], Cesium.Ellipsoid.WGS84, result)
    }
  },
  // 绘制动态线
  drawDynamicLine() {
    viewer.entities.add({
      id: 'DynamicLine' + HandleMeasure.stickMeasureId++,
      name: 'DynamicLine',
      polyline: {
        positions: new Cesium.CallbackProperty(HandleMeasure.updateEndPoint, false),
        width: 6,
        material: new Cesium.PolylineGlowMaterialProperty({
          color: Cesium.Color.GOLD,
          glowPower: 0.25
        })
      }
    })
  },
  // 距离单位配置
  setDistance(d) {
    if (d <= 1000) {
      return d + '米'
    } else if (d > 1000) {
      return (d / 1000).toFixed(2) + '公里'
    }
  },
  // 计算两点距离
  getSpaceDistance(positions) {
    var distance = 0
    for (var i = 0; i < positions.length - 1; i++) {
      /** 根据经纬度计算出距离**/
      var geodesic = new Cesium.EllipsoidGeodesic()
      geodesic.setEndPoints(positions[i], positions[i + 1])
      var s = geodesic.surfaceDistance
      // 返回两点之间的距离
      s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2))
      distance = distance + s
    }

    return distance
  },
  // 求两点的地表距离
  surfaceDistance(positions) {
    const startPosition = new Cesium.Cartographic(positions[0] / (180 / Math.PI), positions[1] / (180 / Math.PI))
    const endPosition = new Cesium.Cartographic(positions[2] / (180 / Math.PI), positions[3] / (180 / Math.PI))
    const geodesic = new Cesium.EllipsoidGeodesic(startPosition, endPosition)
    const distance = geodesic.surfaceDistance // 单位是米
    return distance.toFixed(2)
  },
  // 求两点的直线距离
  linearDistance() {
    const startPosition = new Cesium.Cartesian3.fromDegrees(110, 30)
    const endPosition = new Cesium.Cartesian3.fromDegrees(110, 30.1)
    const distance = Cesium.Cartesian3.distance(startPosition, endPosition)
  },
  handlePickCoordinate(target) {
    HandleMeasure.ispickUpCoordinate = !HandleMeasure.ispickUpCoordinate
    if (HandleMeasure.ispickUpCoordinate) {
      document.getElementById('cesiumContainer').style.cursor = 'crosshair';
    } else {
      document.getElementById('cesiumContainer').style.cursor = 'default';
    }
    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    // 鼠标左键单击事件
    handler.setInputAction((movement) => {
      if (!HandleMeasure.ispickUpCoordinate) {
        handler && handler.destroy() // 关闭事件句柄
        return
      }
      var cartesian2 = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid)
      var cartographic = Cesium.Cartographic.fromCartesian(cartesian2)
      // 将弧度值转为经纬度
      var lng = Cesium.Math.toDegrees(cartographic.longitude)// 经度值
      var lat = Cesium.Math.toDegrees(cartographic.latitude)// 纬度值
      const input = document.createElement('input');
      document.body.appendChild(input);
      input.value = `${lng},${lat}`
      input.select()
      try {
        if (document.execCommand("copy", false)) {
          Message({
            message: '已经复制到剪切板',
            type: 'success'
          });
        } else {
        }
      } catch (error) {
      } finally {
        input.remove();
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    handler.setInputAction(() => {
      HandleMeasure.ispickUpCoordinate = false
      document.getElementById('cesiumContainer').style.cursor = 'default';
      handler && handler.destroy() // 关闭事件句柄
      store.commit('user/SET_measure')
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)

  }
}
export default HandleMeasure
